import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElLoading } from 'element-plus'
import { ILoadingInstance } from 'element-plus/lib/components/loading/src/loading.type'

interface CCRequestInterceptors<T = AxiosResponse> {
  requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig
  requestInterceptorCatch?: (error: any) => any

  responseInterceptor?: (res: T) => T
  responseInterceptorCatch?: (error: any) => any
}

interface CCRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
  interceptors?: CCRequestInterceptors<T>
  showLoading?: boolean
}

const IS_LOADING = true

class CCRequest<T> {
  instance: AxiosInstance
  interceptors?: CCRequestInterceptors
  loadingCtl?: ILoadingInstance
  showLoading?: boolean

  constructor(config: CCRequestConfig) {
    this.instance = axios.create(config)

    // 自定义的每个实例独有的拦截器
    this.interceptors = config.interceptors
    this.instance.interceptors.request.use(this.interceptors?.requestInterceptor, this.interceptors?.responseInterceptorCatch)

    this.instance.interceptors.response.use(this.interceptors?.responseInterceptor, this.interceptors?.responseInterceptorCatch)

    // 所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 请求拦截器
        console.log('所有实例都有的请求拦截器')

        if (this.showLoading) {
          this.loadingCtl = ElLoading.service({
            lock: true,
            text: '努力加载中...',
            background: 'rgba(0,0,0,0.5)'
          })
        }

        return config
      },
      (error) => error
    )

    this.instance.interceptors.response.use(
      (res) => {
        // 响应拦截器
        console.log('所有实例都有的响应拦截器')

        // 延迟显式响应来的结果，测试用
        // setTimeout(() => {
        //   this.loadingCtl?.close()
        // }, 3000)
        this.loadingCtl?.close()

        return res.data
      },
      (error) => error
    )
  }

  request<T = any>(config: CCRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 应用加载文案
      this.showLoading = config.showLoading ?? IS_LOADING

      if (config.interceptors?.requestInterceptor) {
        // 单个请求设置了请求拦截器时将用户自定义的拦截器集成到 config 后提供给 axios 使用 - 单个请求的拦截器才能生效
        config = config.interceptors.requestInterceptor(config)
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            // 实现单个响应的拦截器
            res = config.interceptors.responseInterceptor(res)
          }
          console.log(res)

          // 每次请求之后设置默认显式 loading
          this.showLoading = IS_LOADING
          resolve(res)
        })
        .catch((error) => {
          // 请求成功或者失败都要恢复默认显式 loading
          this.showLoading = IS_LOADING
          reject(error)
          return error
        })
    })
  }

  get<T = any>(config: CCRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }

  post<T = any>(config: CCRequestConfig<T>): Promise<T> {
    console.log('srcserivce\requestindex.ts#post:', config)
    return this.request<T>({ ...config, method: 'POST' })
  }

  delete<T = any>(config: CCRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }

  patch<T = any>(config: CCRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}

export default CCRequest
